<?php

namespace app\common\model\hfztcy;

use app\common\model\BaseModel;
use app\common\model\LibAdmin;
use app\common\model\LibUser;
use common\Common;
use think\Db;
use think\Exception;

// 单次付费看视频
//direct_user_id 直推用户
//private_red_mother_id 专属红娘用户
//shi_admin_id 市代用户
//xian_admin_id 区县代用户

// 开通红娘
//direct_user_id 直推红娘
//indirect_user_id 间推红娘
//shi_admin_id 市代用户
//xian_admin_id 区县代用户
//kf_admin_id 客服部用户
//px_admin_id 培训部用户

// vip套餐订单
//shi_admin_id 市代用户
//xian_admin_id 区县代用户

// 栏目认证
//direct_user_id 直推红娘
//indirect_user_id 间推红娘
//store_user_id 门店用户
//store_parent_user_id 门店上级用户
//shi_admin_id 市代用户
//xian_admin_id 区县代用户
//kf_admin_id 客服部用户
//px_admin_id 培训部用户

/**
 * 分销逻辑
 * @name LibDistribute.php
 * @package hfztcy
 * @category model
 * @link http://www.chanekeji.com
 * @author rxy
 * @version 1.0
 * @copyright CHANGE INC
 * @since 2022-06-17
 */
class LibDistribute extends BaseModel
{
    public $order;
    public $logPath;
    public $paymentUser;
    public $wxUserModel;
    public $wxUser;
    public $orderType = 0;

    public function __construct($order)
    {
        $this->order = $order;
        $this->logPath = ROOT_PATH . "public/pay/pay{$order['id']}.log";
        parent::__construct();
    }

    /**
     * Info: 设置订单类型 0单次看视频订单1VIP套餐订单2红娘开通订单3栏目认证订单
     * Date: 2023/1/9 15:32
     */
    public function setOrderType ($type)
    {
        $this->orderType = $type;
        return $this;
    }

    private function write_file($text)
    {
        //dump($this->logPath);
        if (@$fp = fopen($this->logPath, 'a')) {
            flock($fp, 2);
            fwrite($fp, $text . "\r\n");
            fclose($fp);
        }
    }

    /**
     * Info: 会员分销记录
     * Date: 2022/11/18 9:18
     */
    private function addCommissionRecords($user_id, $describe, $before_balance, $amount)
    {
        $data = [];
        $data['user_id'] = $user_id;
        $data['describe'] = $describe;
        $data['before_balance'] = $before_balance;
        $data['amount'] = $amount;
        $data['add_time'] = Common::getTime();
        $data['order_id'] = $this->order['id'];
        $data['type'] = $this->orderType;
        $data['zj_state'] = in_array($this->orderType,[2,3]) ? 1 : 0;//佣金状态 0可提现 1冻结中 2已失效
        $data['order_info'] = json_encode($this->order, JSON_UNESCAPED_UNICODE);
        $model = new LibBalanceRecords();
        $model->addCommissionRecords($data);
        return $model->getLastSql();
    }

    /**
     * Info: 代理商、客服部、培训部分销记录
     * Date: 2022/11/18 9:19
     */
    private function addAdminCommissionRecords($user_id, $describe, $before_balance, $amount, $state)
    {
        $data = [];
        $data['user_id'] = $user_id;
        $data['describe'] = $describe;
        $data['before_balance'] = $before_balance;
        $data['amount'] = $amount;
        $data['state'] = $state;
        $data['add_time'] = Common::getTime();
        $data['order_id'] = $this->order['id'];
        $data['type'] = $this->orderType;
        $data['zj_state'] = in_array($this->orderType,[2,3]) ? 1 : 0;//佣金状态 0可提现 1冻结中 2已失效
        $data['order_info'] = json_encode($this->order, JSON_UNESCAPED_UNICODE);
        $model = new LibAdminBalanceRecords();
        $model->addCommissionRecords($data);
        return $model->getLastSql();
    }

    /**
     * Info: 设置佣金
     * Date: 2022/11/18 9:19
     */
    private function _set_commission_records($user_id, $balance, $money, $type)
    {
        $typeStr = '';
        if ($type == 0) $typeStr = '付费看视频';
        if ($type == 1) $typeStr = '购买VIP套餐';
        if ($type == 2) $typeStr = '栏目认证';
        if ($type == 3) $typeStr = '红娘认证';
        $info = $this->paymentUser['username'] . $typeStr . '，可得佣金：' . $money;
        if (floatval($money) <= 0) return false;
        return $this->addCommissionRecords($user_id, $info, $balance, $money);
    }

    /**
     * Info: 设置佣金
     * Date: 2022/11/25 19:45
     */
    private function _set_admin_commission_records ($user_id, $balance, $money, $type,$identity,$state)
    {
        $typeStr = '';
        if ($type == 0) $typeStr = '付费看视频';
        if ($type == 1) $typeStr = '购买VIP套餐';
        if ($type == 2) $typeStr = '栏目认证';
        if ($type == 3) $typeStr = '红娘认证';
        $info = $this->paymentUser['username'] . $typeStr . '，'.$identity.'可得佣金：' . $money;
        if (floatval($money) <= 0) return false;
        return $this->addAdminCommissionRecords($user_id, $info, $balance, $money, $state);
    }

    /**
     * Info: 设置用户余额
     * Date: 2022/11/18 9:19
     */
    private function _set_user_balance($model, $pk, $total_balance, $balance, $money, $user_id)
    {
        //if (in_array($this->orderType,[2,3])) return '';
        $total_balance = (float)$total_balance + (float)$money;//累计佣金
        $balance = (float)$balance + (float)$money;//佣金
        if ($pk == 'id') {
            $model->updateUser([$pk => $user_id], [
                'total_balance' => $total_balance,
                'balance' => $balance,
            ]);
        } else {
            $model->updateMember([$pk => $user_id], [
                'total_balance' => $total_balance,
                'balance' => $balance,
            ]);
        }
        return $model->getLastSql();
    }

    /**
     * Info: 设置管理员余额
     * Date: 2022/11/18 9:19
     */
    private function _set_admin_balance($model, $pk, $total_balance, $balance, $money, $user_id)
    {
        //if (in_array($this->orderType,[2,3])) return '';
        $total_balance = (float)$total_balance + (float)$money;//累计佣金
        $balance = (float)$balance + (float)$money;//佣金
        $model->updateAdmin([$pk => $user_id], [
            'total_balance' => $total_balance,
            'balance' => $balance,
        ]);
        return $model->getLastSql();
    }


    // 红娘购买成功，7天之内产生的收益进入冻结收益中。

    /**
     * Info: 直推用户【单次付费看视频】【红娘认证】【栏目认证】
     * Date: 2022/11/18 9:19
     */
    private function getDirectUser($memberModel)
    {
        $result = [];
        $this->write_file('直推用户');
        if (isset($this->order['direct_user_id']) && $this->order['direct_user_id']) {
            $findDirectUserRes = $this->wxUserModel->findUser(['id' => $this->order['direct_user_id']]);
            $directUserInfo = $findDirectUserRes['data'];
            $this->write_file('直推用户：' . $this->order['direct_user_id']);
            $this->write_file('直推用户身份：' . $directUserInfo['identity']);
            $this->write_file('直推用户佣金：' . $this->order['zt_commission_money']);
            if (strpos($directUserInfo['identity'], '0') !== false) { //是游客
                // 更新微信用户信息
                $sql1 = $this->_set_user_balance($this->wxUserModel, 'id', $directUserInfo['total_balance'], $directUserInfo['balance'], $this->order['zt_commission_money'], $this->order['direct_user_id']);
                $this->write_file('更新会员佣金SQL：' . $sql1);
                // 添加会员佣金记录
                $sql2 = $this->_set_commission_records($this->order['direct_user_id'], $directUserInfo['balance'], $this->order['zt_commission_money'], $this->order['type']);
                $this->write_file('佣金记录SQL：' . $sql2);
                $result[] = [
                    'update_member_balance_sql' => $sql1,
                    'create_member_commission_record_sql' => $sql2
                ];
            } else {
                $findDirectMemberRes = $memberModel->findMember(['user_id' => $this->order['direct_user_id']]);
                if ($findDirectMemberRes['errorCode'] == 0) {
                    $directMemberInfo = $findDirectMemberRes['data'];
                    // 更新会员表信息
                    $sql1 = $this->_set_user_balance($memberModel, 'user_id', $directMemberInfo['total_balance'], $directMemberInfo['balance'], $this->order['zt_commission_money'], $this->order['direct_user_id']);
                    $this->write_file('更新会员佣金SQL：' . $sql1);
                    $sql2 = $this->_set_user_balance($this->wxUserModel, 'id', $directMemberInfo['total_balance'], $directMemberInfo['balance'], $this->order['zt_commission_money'], $this->order['direct_user_id']);
                    $this->write_file('更新会员佣金SQL：' . $sql2);
                    // 添加会员佣金记录
                    $sql3 = $this->_set_commission_records($this->order['direct_user_id'], $directMemberInfo['balance'], $this->order['zt_commission_money'], $this->order['type']);
                    $this->write_file('佣金记录SQL：' . $sql3);
                    $result[] = [
                        'update_member_balance1_sql' => $sql1,
                        'update_member_balance2_sql' => $sql2,
                        'create_member_commission_record_sql' => $sql3
                    ];
                }
            }
        }
        return $result;
    }

    /**
     * Info: 间推用户【红娘认证】【栏目认证】
     * Date: 2022/11/18 9:43
     */
    private function getIndirectUser($memberModel)
    {
        $result = [];
        $this->write_file('间推用户');
        if (isset($this->order['indirect_user_id']) && $this->order['indirect_user_id']) {
            $this->write_file('间推用户：' . $this->order['indirect_user_id']);
            $findMemberRes = $memberModel->findMember(['user_id' => $this->order['indirect_user_id']]);
            if ($findMemberRes['errorCode'] == 0) {
                $memberInfo = $findMemberRes['data'];
                $this->write_file('间推用户身份：' . $memberInfo['state']);
                $this->write_file('间推用户佣金：' . $this->order['jt_commission_money']);
                // 更新会员信息
                $sql1 = $this->_set_user_balance($memberModel, 'user_id', $memberInfo['total_balance'], $memberInfo['balance'], $this->order['jt_commission_money'], $this->order['indirect_user_id']);
                $this->write_file('更新会员佣金SQL：' . $sql1);
                // 更新微信用户信息
                $sql2 = $this->_set_user_balance($this->wxUserModel, 'id', $memberInfo['total_balance'], $memberInfo['balance'], $this->order['jt_commission_money'], $this->order['indirect_user_id']);
                $this->write_file('更新会员佣金SQL：' . $sql2);
                // 添加会员佣金记录
                $sql3 = $this->_set_commission_records($this->order['indirect_user_id'], $memberInfo['balance'], $this->order['jt_commission_money'], $this->order['type']);
                $this->write_file('佣金记录SQL：' . $sql3);
                $result[] = [
                    'update_member_balance1_sql' => $sql1,
                    'update_member_balance2_sql' => $sql2,
                    'create_member_commission_record_sql' => $sql3
                ];
            }
        }
        return $result;
    }

    /**
     * Info: 专属红娘【单次付费看视频】
     * Date: 2022/11/18 9:44
     */
    private function getPrivateRedMotherUser($memberModel)
    {
        $result = [];
        $this->write_file('专属红娘');
        if (isset($this->order['private_red_mother_id']) && $this->order['private_red_mother_id']) {
            $this->write_file('专属红娘：' . $this->order['private_red_mother_id']);
            $findMemberRes = $memberModel->findMember(['user_id' => $this->order['private_red_mother_id']]);
            if ($findMemberRes['errorCode'] == 0) {
                $memberInfo = $findMemberRes['data'];
                $this->write_file('专属红娘佣金：' . $this->order['zs_commission_money']);
                // 更新会员信息
                $sql1 = $this->_set_user_balance($memberModel, 'user_id', $memberInfo['total_balance'], $memberInfo['balance'], $this->order['zs_commission_money'], $this->order['private_red_mother_id']);
                $this->write_file('更新会员佣金SQL：' . $sql1);
                // 更新微信用户信息
                $update_direct_user_sql = $this->_set_user_balance($this->wxUserModel, 'id', $memberInfo['total_balance'], $memberInfo['balance'], $this->order['zs_commission_money'], $this->order['private_red_mother_id']);
                $this->write_file('更新会员佣金SQL：' . $update_direct_user_sql);
                // 添加会员佣金记录
                $sql2 = $this->_set_commission_records($this->order['private_red_mother_id'], $memberInfo['balance'], $this->order['zs_commission_money'], $this->order['type']);
                $this->write_file('佣金记录SQL：' . $sql2);
                $result[] = [
                    'update_private_red_mother_sql' => $sql1,
                    'create_member_commission_record_sql' => $sql2
                ];
            }
        }
        return $result;
    }

    /**
     * Info: 门店【单次付费看视频】
     * Date: 2022/11/18 9:44
     */
    private function getStoreBySeeVideo ($memberModel)
    {
        $result = [];
        $this->write_file('门店');
        if (isset($this->order['store_user_id']) && $this->order['store_user_id']) {
            $this->write_file('门店用户：' . $this->order['store_user_id']);
            $findMemberRes = $memberModel->findMember(['user_id' => $this->order['store_user_id']]);
            if ($findMemberRes['errorCode'] == 0) {
                $memberInfo = $findMemberRes['data'];
                $this->write_file('门店用户佣金：' . $this->order['md_commission_money']);
                // 更新会员信息
                $sql1 = $this->_set_user_balance($memberModel, 'user_id', $memberInfo['total_balance'], $memberInfo['balance'], $this->order['md_commission_money'], $this->order['store_user_id']);
                $this->write_file('更新会员佣金SQL：' . $sql1);
                // 更新微信用户信息
                $sql2 = $this->_set_user_balance($this->wxUserModel, 'id', $memberInfo['total_balance'], $memberInfo['balance'], $this->order['md_commission_money'], $this->order['store_user_id']);
                $this->write_file('更新会员佣金SQL：' . $sql2);
                // 添加会员佣金记录
                $sql3 = $this->_set_commission_records($this->order['store_user_id'], $memberInfo['balance'], $this->order['md_commission_money'], $this->order['type']);
                $this->write_file('佣金记录SQL：' . $sql3);
                $result[] = [
                    'update_store_sql1' => $sql1,
                    'update_store_sql2' => $sql2,
                    'create_member_commission_record_sql' => $sql3
                ];
            }
        }
        return $result;
    }

    /**
     * Info: 市代理商【单次付费看视频】【红娘认证】【栏目认证】【VIP套餐】
     * Date: 2022/11/18 9:44
     */
    private function getAgentByShi($adminModel)
    {
        $result = [];
        $this->write_file('市代理商');
        if (isset($this->order['shi_admin_id']) && $this->order['shi_admin_id']) {
            $this->write_file('市代理商：' . $this->order['shi_admin_id']);
            $findMemberRes = $adminModel->findAdmin(['id' => $this->order['shi_admin_id']]);
            if ($findMemberRes['errorCode'] == 0) {
                $memberInfo = $findMemberRes['data'];
                $this->write_file('市代理商佣金：' . $this->order['shi_commission_money']);
                // 更新会员信息
                $update_admin_shi_sql = $this->_set_admin_balance($adminModel, 'id', $memberInfo['total_balance'], $memberInfo['balance'], $this->order['shi_commission_money'], $this->order['shi_admin_id']);
                $this->write_file('更新会员SQL：' . $update_admin_shi_sql);
                // 添加会员佣金记录
                $sql = $this->_set_admin_commission_records($this->order['shi_admin_id'],$memberInfo['balance'],$this->order['shi_commission_money'],$this->order['type'],'市代理商',1);
                $this->write_file('佣金记录SQL：' . $sql);
                $result[] = [
                    'update_admin_shi_sql' => $update_admin_shi_sql,
                    'create_admin_commission_record_sql' => $sql
                ];
            }
        }
        return $result;
    }

    /**
     * Info: 区县代理商【单次付费看视频】【红娘认证】【栏目认证】【VIP套餐】
     * Date: 2022/11/18 9:45
     */
    private function getAgentByXian($adminModel)
    {
        $result = [];
        $this->write_file('区县代理商');
        if (isset($this->order['xian_admin_id']) && $this->order['xian_admin_id']) {
            $this->write_file('区县代理商：' . $this->order['xian_admin_id']);
            $findMemberRes = $adminModel->findAdmin(['id' => $this->order['xian_admin_id']]);
            if ($findMemberRes['errorCode'] == 0) {
                $memberInfo = $findMemberRes['data'];
                $this->write_file('区县代理商佣金：' . $this->order['xian_commission_money']);
                // 更新会员信息
                $update_admin_xian_sql = $this->_set_admin_balance($adminModel, 'id', $memberInfo['total_balance'], $memberInfo['balance'], $this->order['xian_commission_money'], $this->order['xian_admin_id']);
                $this->write_file('更新会员SQL：' . $update_admin_xian_sql);
                // 添加会员佣金记录
                $sql = $this->_set_admin_commission_records($this->order['xian_admin_id'],$memberInfo['balance'],$this->order['xian_commission_money'],$this->order['type'],'区县代理商',1);
                $this->write_file('佣金记录SQL：' . $sql);
                $result[] = [
                    'update_admin_shi_sql' => $update_admin_xian_sql,
                    'create_admin_commission_record_sql' => $sql
                ];
            }
        }
        return $result;
    }

    /**
     * Info: 客服部【红娘认证】【栏目认证】
     * Date: 2022/11/18 9:46
     */
    private function getCustomerUser($adminModel)
    {
        $result = [];
        $this->write_file('客服部');
        if (isset($this->order['kf_admin_id']) && $this->order['kf_admin_id']) {
            $this->write_file('客服部：' . $this->order['kf_admin_id']);
            $findMemberRes = $adminModel->findAdmin(['id' => $this->order['kf_admin_id']]);
            if ($findMemberRes['errorCode'] == 0) {
                $memberInfo = $findMemberRes['data'];
                $this->write_file('客服部佣金：' . $this->order['kf_commission_money']);
                // 更新会员信息
                $update_admin_kf_sql = $this->_set_admin_balance($adminModel, 'id', $memberInfo['total_balance'], $memberInfo['balance'], $this->order['kf_commission_money'], $this->order['kf_admin_id']);
                $this->write_file('更新会员SQL：' . $update_admin_kf_sql);
                // 添加会员佣金记录
                $sql = $this->_set_admin_commission_records($this->order['kf_admin_id'],$memberInfo['balance'],$this->order['kf_commission_money'],$this->order['type'],'客服部',2);
                $this->write_file('佣金记录SQL：' . $sql);
                $result[] = [
                    'update_admin_kf_sql' => $update_admin_kf_sql,
                    'create_admin_commission_record_sql' => $sql
                ];

                // 给客服部各员工分润
                $kfbStaffListRes = $adminModel->findAllAdmin(['bid' => $this->order['kf_admin_id']]);
                if ($kfbStaffListRes['errorCode'] == 0) {
                    array_map(function ($staff) use ($adminModel) {
                        if (floatval($staff['rate'])) {
                            $staff_commission_money = $staff['rate'] * $this->order['kf_commission_money'];
                            $staff_commission_money = (float)sprintf("%.2f", substr(sprintf("%.3f", $staff_commission_money), 0, -1));
                            $this->_set_admin_balance($adminModel, 'id', $staff['total_balance'], $staff['balance'], $staff_commission_money, $staff['id']);
                            $this->_set_admin_commission_records($staff['id'],$staff['balance'],$staff_commission_money,$this->order['type'],'客服部员工',4);
                        }
                    },$kfbStaffListRes['data']);
                }
            }
        }
        return $result;
    }

    /**
     * Info: 培训部 【红娘认证】【栏目认证】
     * Date: 2022/11/18 9:46
     */
    private function getTrainUser($adminModel)
    {
        $result = [];
        $this->write_file('培训部');
        if (isset($this->order['px_admin_id']) && $this->order['px_admin_id']) {
            $this->write_file('培训部：' . $this->order['px_admin_id']);
            $findMemberRes = $adminModel->findAdmin(['id' => $this->order['px_admin_id']]);
            if ($findMemberRes['errorCode'] == 0) {
                $memberInfo = $findMemberRes['data'];
                $this->write_file('培训部佣金：' . $this->order['px_commission_money']);
                // 更新会员信息
                $update_admin_px_sql = $this->_set_admin_balance($adminModel, 'id', $memberInfo['total_balance'], $memberInfo['balance'], $this->order['px_commission_money'], $this->order['px_admin_id']);
                $this->write_file('更新会员SQL：' . $update_admin_px_sql);
                // 添加会员佣金记录
                $sql = $this->_set_admin_commission_records($this->order['px_admin_id'],$memberInfo['balance'],$this->order['px_commission_money'],$this->order['type'],'培训部',3);
                $this->write_file('佣金记录SQL：' . $sql);
                $result[] = [
                    'update_admin_px_sql' => $update_admin_px_sql,
                    'create_admin_commission_record_sql' => $sql
                ];

                // 给客服部各员工分润
                $pxbStaffListRes = $adminModel->findAllAdmin(['bid' => $this->order['px_admin_id']]);
                if ($pxbStaffListRes['errorCode'] == 0) {
                    array_map(function ($staff) use ($adminModel) {
                        if (floatval($staff['rate'])) {
                            $staff_commission_money = $staff['rate'] * $this->order['px_commission_money'];
                            $staff_commission_money = (float)sprintf("%.2f", substr(sprintf("%.3f", $staff_commission_money), 0, -1));
                            $this->_set_admin_balance($adminModel, 'id', $staff['total_balance'], $staff['balance'], $staff_commission_money, $staff['id']);
                            $this->_set_admin_commission_records($staff['id'],$staff['balance'],$staff_commission_money,$this->order['type'],'培训部员工',5);
                        }
                    },$pxbStaffListRes['data']);
                }
            }
        }
        return $result;
    }


    // 1、先处理门店分润
    // 2、在处理门店上级推荐人分润比例
    /**
     * Info: 门店 【栏目认证】
     * Date: 2022/11/18 9:47
     */
    private function getStore($memberModel)
    {
        $result = [];
        $this->write_file('门店');
        if (isset($this->order['store']) && $this->order['store_id'])
        {
            $this->write_file('门店：' . $this->order['store_id']);
            // 绑定的门店用户
            $findMemberRes = $memberModel->findMember(['user_id' => $this->order['store']['uid']]);
            if ($findMemberRes['errorCode'] == 0)
            {
                // 栏目认证配置参数
                $configModel = new LibConfig();
                $findConfigRes = $configModel->findConfig(['item_key' => 'vip_video_auth_rate']);
                $rateList = json_decode($findConfigRes['data']['item_value'], true);
                if ($rateList['store'])
                {
                    // 扣除制作费
                    $amount =  $this->order['amount'] - (float)$rateList['amount'];
                    if ($amount <= 0) {
                        return $result;
                    }
                    // 直推红娘信息
                    $memberInfo = $findMemberRes['data'];
                    $store_point_user_rate = (float)$rateList['store_point_user'];//门店抽取直推红娘多少分润比例
                    // 判断是否为门店派单
                    if ($this->order['is_offline'] == 1) {//表示用户指定门店
                        $rate = (float)$rateList['store'] + $store_point_user_rate;
                    } else {//表示后台指定门店
                        $rate = (float)$rateList['store'];
                    }
                    // 单独计算门店抽取红娘直推分润比例
                    // 判断直推用户是否存在
                    $store_point_user_commission_money = 0;
                    if ($this->order['is_offline'] == 1 && isset($this->order['direct_user_id']) && $this->order['direct_user_id']) {
                        $findDirectMemberRes = $memberModel->findMember(['user_id' => $this->order['direct_user_id']]);
                        if ($findDirectMemberRes['errorCode'] == 0) {
                            $directMemberInfo = $findDirectMemberRes['data'];
                            $store_point_user_commission_money = ($amount * $store_point_user_rate);
                            $store_point_user_commission_money = (float)sprintf("%.2f", substr(sprintf("%.3f", $store_point_user_commission_money), 0, -1));
                            $this->write_file('门店佣金：' . $store_point_user_commission_money);
                            // 更新会员表信息
                            $update_direct_user1_sql = $this->_set_user_balance($memberModel, 'user_id', $directMemberInfo['total_balance'], $directMemberInfo['balance'], $store_point_user_commission_money, $this->order['store']['uid']);
                            $this->write_file('更新会员佣金SQL：' . $update_direct_user1_sql);
                            $update_direct_user2_sql = $this->_set_user_balance($this->wxUserModel, 'id', $directMemberInfo['total_balance'], $directMemberInfo['balance'], $store_point_user_commission_money, $this->order['store']['uid']);
                            $this->write_file('更新会员佣金SQL：' . $update_direct_user2_sql);
                            // 添加佣金记录
                            $describe = $this->paymentUser['username']."栏目认证，门店从直推红娘抽拥：{$store_point_user_commission_money}";
                            $add_commission_record1_sql = $this->addCommissionRecords($this->order['store']['user_id'],$describe,$directMemberInfo['balance'],$store_point_user_commission_money);
                            $this->write_file('门店抽取红娘佣金记录SQL：' . $add_commission_record1_sql);
                            // 更新订单
                            (new LibOrderVipAuth())->updateOrder(['order_id' => $this->order['id']], [
                                'md_give_red_mother_commission_money' => abs($store_point_user_commission_money)//门店抽取红娘佣金
                            ]);
                        }
                    }
                    // 门店佣金
                    $store_commission_money_total = ($amount * $rate);
                    $store_commission_money = (float)sprintf("%.2f", substr(sprintf("%.3f", $store_commission_money_total), 0, -1));
                    $store_commission_money = $store_commission_money - $store_point_user_commission_money;
                    // 添加佣金记录
                    $add_commission_record1_sql = $this->_set_commission_records($this->order['store']['uid'], $memberInfo['balance'], $store_commission_money, $this->order['type']);
                    $this->write_file('门店本身的佣金记录SQL：' . $add_commission_record1_sql);
                    // 更新订单
                    (new LibOrderVipAuth())->updateOrder(['order_id' => $this->order['id']], [
                        'store_user_id' => $this->order['store']['uid'],
                        'md_commission_money' => abs($store_commission_money)
                    ]);
                    $this->write_file('门店佣金：' . $store_commission_money);
                    // 重新获取用户信息
                    $findMemberRes = $memberModel->findMember(['user_id' => $this->order['store']['uid']]);
                    $memberInfo = $findMemberRes['data'];
                    // 更新会员余额
                    $update_store1_sql = $this->_set_user_balance($memberModel, 'user_id', $memberInfo['total_balance'], $memberInfo['balance'], $store_commission_money, $this->order['store']['uid']);
                    $this->write_file('更新会员佣金SQL：' . $update_store1_sql);
                    // 更新微信用户信息
                    $update_store2_sql = $this->_set_user_balance($this->wxUserModel, 'id', $memberInfo['total_balance'], $memberInfo['balance'], $store_commission_money, $this->order['store']['uid']);
                    $this->write_file('更新会员佣金SQL：' . $update_store2_sql);

                    // 给门店上级增加佣金
                    $update_store_parent1_sql = $update_store_parent2_sql = $add_commission_record2_sql = '';
                    if ($rateList['store_direct_user']) {
                        $res = $this->getStoreParentUserCommission($store_commission_money_total,$rateList, $rate,$memberModel);
                        if ($res) {
                            $update_store_parent1_sql = $res['update_store_parent1_sql'];
                            $update_store_parent2_sql = $res['update_store_parent2_sql'];
                            $add_commission_record2_sql = $res['add_commission_record2_sql'];
                        }
                    }

                    $result[] = [
                        'update_store1_sql' => $update_store1_sql,
                        'update_store2_sql' => $update_store2_sql,
                        'create_member_commission_record_sql' => $add_commission_record1_sql,
                        'update_store_parent1_sql' => $update_store_parent1_sql,
                        'update_store_parent2_sql' => $update_store_parent2_sql,
                        'add_commission_record2_sql' => $add_commission_record2_sql,
                    ];
                }
            }
        }
        return $result;
    }

    // 门店上级推荐人佣金 门店上级推荐人要么获得订单总额的2%收益 要么是获得3%收益
    private function getStoreParentUserCommission ($store_commission_money,$rateList,$rate,$memberModel)
    {
        $result = [];
        // 绑定的店铺用户
        $findUserRes = $this->wxUserModel->findUser(['id' => $this->order['store']['uid']]);
        if ($findUserRes['errorCode'] == 0 && $findUserRes['data']['parent_id'])
        {
            // 获取上级推荐人
            $findParentUserRes = $this->wxUserModel->findUser(['id' => $this->order['store']['user_id']]);
            if ($findParentUserRes['errorCode'] == 0)
            {
                $bili = (float)$rateList['store_direct_user'] * $rate;
                $this->write_file('上级推荐人分润比例：' . $bili);
                // 门店上级佣金
                $store_parent_user_commission_money = $store_commission_money * $bili;
                // 上级推荐人信息
                $memberInfo = $findParentUserRes['data'];
                // 更新订单
                (new LibOrderVipAuth())->updateOrder(['order_id' => $this->order['id']], [
                    'store_parent_user_id' => $findUserRes['data']['parent_id'],
                    'store_parent_user_commission_money' => abs($store_parent_user_commission_money)
                ]);
                $this->write_file('门店上级佣金：' . $store_parent_user_commission_money);
                // 更新会员余额
                $update_store_parent1_sql = $this->_set_user_balance($memberModel, 'user_id', $memberInfo['total_balance'], $memberInfo['balance'], $store_parent_user_commission_money, $this->order['store']['user_id']);
                $this->write_file('更新会员佣金SQL：' . $update_store_parent1_sql);
                // 更新微信用户信息
                $update_store_parent2_sql = $this->_set_user_balance($this->wxUserModel, 'id', $memberInfo['total_balance'], $memberInfo['balance'], $store_parent_user_commission_money, $this->order['store']['user_id']);
                $this->write_file('更新会员佣金SQL：' . $update_store_parent2_sql);
                // 添加佣金记录
                $describe = $this->paymentUser['username']."栏目认证，门店给您的佣金：{$store_parent_user_commission_money}";
                $add_commission_record2_sql = $this->addCommissionRecords($findUserRes['data']['parent_id'],$describe,$memberInfo['balance'],$store_parent_user_commission_money);
                $this->write_file('佣金记录SQL：' . $add_commission_record2_sql);
                return [
                    'update_store_parent1_sql' => $update_store_parent1_sql,
                    'update_store_parent2_sql' => $update_store_parent2_sql,
                    'add_commission_record2_sql' => $add_commission_record2_sql,
                ];
            }
        }
        return $result;
    }

    /**
     * Info: 分销方法
     * Date: 2022/11/18 9:47
     */
    public function updateUserBalance()
    {
        $memberModel = new LibMember();
        $adminModel = new LibAdmin();
        $this->wxUserModel = new LibUser();
        // 已注册的用户信息
        $findMemberRes = $memberModel->findMember(['user_id' => $this->order['user_id']]);
        $this->paymentUser = $findMemberRes['data'];
        // 微信用户表信息
        $this->wxUser = $this->wxUserModel->findUser(['id' => $this->order['user_id']]);

        // 佣金类型
        $arr = [0 => '单次看视频订单', 1=>'VIP套餐订单',2 => '红娘开通订单', 3 => '栏目认证订单'];
        $this->write_file('佣金类型：' . $arr[$this->orderType]);

        Db::startTrans();
        try {
            $result = [];
            // 直推用户
            $result[0] = $this->getDirectUser($memberModel);
            // 间推用户
            $result[1] = $this->getIndirectUser($memberModel);
            // 专属红娘
            $result[2] = $this->getPrivateRedMotherUser($memberModel);
            // 市代用户
            $result[3] = $this->getAgentByShi($adminModel);
            // 区县代用户
            $result[4] = $this->getAgentByXian($adminModel);
            // 客服部用户
            $result[5] = $this->getCustomerUser($adminModel);
            // 培训部用户
            $result[6] = $this->getTrainUser($adminModel);
            // 门店
            if ($this->order['type'] == 2) {
                $result[7] = $this->getStore($memberModel);
            } else {
                $result[7] = $this->getStoreBySeeVideo($memberModel);
            }

            // 更新佣金发放状态
            (new LibOrder())->updateOrder(['id' => $this->order['id']] , ['delivery_state' => 1,'delivery_time' => Common::getTime()]);
            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
        }
        return $result;
    }
}

?>